﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using POSSystem.BLL;

namespace MobileShop
{
    public partial class Product : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadProduct();
            }
        }

        int ProductID
        {
            get
            {
                if (string.IsNullOrEmpty(Request.QueryString["product"]))
                    return 0;
                return MobileShop.Utilities.GetParmValue(Request.QueryString["product"]);
            }
        }

        bool AddedToCart
        {
            get
            {
                return lblAddCart.Visible;
            }
            set
            {
                lblAddCart.Visible = value;
                btnAddCart.Visible = !value;
            }
        }

        bool AddedToWishlist
        {
            get
            {
                return lblAddWishList.Visible;
            }
            set
            {
                lblAddWishList.Visible = value;
                btnAddWishList.Visible = !value;
            }
        }

        string GetRPPPrice(POSSystem.BLL.View_WebProducts product)
        {
            return string.IsNullOrEmpty(product.s_RegularPrice) ? "" : "<span class='productDetailLabel' style=' font-weight:bold; text-decoration:line-through'>Regular Price: <span class='productDetailLabel' style='color:red; font-weight:bold; text-decoration:line-through'>" + string.Format("{0:C}", product.RegularPrice) + "</span></span><br/>";
        }

        string GetPrice(POSSystem.BLL.View_WebProducts product)
        {
            if (View_Customers.GetCurrentUser() == null)
                return string.Format("{0:C}", product.SalePrice);

            return string.Format("{0:C}", (View_Customers.GetCurrentUser().Price == CustomerType.CustomerPrice.SalePrice) ? product.SalePrice : (View_Customers.GetCurrentUser().Price == CustomerType.CustomerPrice.DealerPrice ? product.DealerPrice : product.PartnerPrice));
        }

        string GetRawPrice(POSSystem.BLL.View_WebProducts product)
        {
            if (View_Customers.GetCurrentUser() == null)
                return string.Format("{0:C}", product.SalePrice);
            return string.Format("{0}", (View_Customers.GetCurrentUser().Price == CustomerType.CustomerPrice.SalePrice) ? product.SalePrice : (View_Customers.GetCurrentUser().Price == CustomerType.CustomerPrice.DealerPrice ? product.DealerPrice : product.PartnerPrice));
        }

        public string GetPicture(POSSystem.BLL.View_WebProducts product)
        {
            ProductImages img = ProductImages.GetDefaultPicture(product.ID);
            return img.RowCount == 0 || img.s_OriginalUrl == "" ? "~/images/emty-big.png" : MobileShop.Utilities.GetImageUrl(img.s_ThumbUrl.ToString());
        }

        public string GetStatus(POSSystem.BLL.View_WebProducts product)
        {
            return product.Quantity > 0 ? "<span style='color:#ff339c'>In Stock </span><img align='top' src='" + this.ResolveClientUrl("~/images/icon_check.gif") + "' />" : "<span style='color:grey'>Back Order</span>";
        }

        protected void LoadProduct()
        {
            View_WebProducts prd = View_WebProducts.LoadProductByID(ProductID);
            if (prd.RowCount == 0)
                return;

            BasePage.SelectedItems.Filter = OrderItems.ColumnNames.ProductID + "=" + ProductID.ToString();
            if (BasePage.SelectedItems.RowCount > 0)
            {
                AddedToCart = true;
            }
            BasePage.SelectedItems.Filter = "";

            if (View_Customers.GetCurrentUser() != null && View_Customers.GetCurrentUser().RowCount > 0)
            {
                View_WishList wish = new View_WishList();
                wish.Where.CustomerID.Value = View_Customers.GetCurrentUser().ID;
                wish.Where.ProductID.Value = ProductID;
                wish.Query.Load();

                if (wish.RowCount > 0)
                {
                    AddedToWishlist = true;
                }
            }

            ProductImages imgs = new ProductImages();
            imgs.Search(ProductImages.ColumnNames.ProductID + "=" + prd.ID + " and Deleted = 0", "*", "", 0, 99);
            rptImages.DataSource = imgs.DefaultView;
            rptImages.DataBind();

            imgProduct.ImageUrl = GetPicture(prd);
            lblProductName.Text = prd.s_ProductName;
            lblPrice.Text = GetPrice(prd);
            litRegularPrice.Text = GetRPPPrice(prd);
            litStatus.Text = GetStatus(prd);
            litDesc.Text = prd.s_Description == "" ? "n/a" : prd.s_Description;
            if (prd.IsNewArrival)
            {
                PageMap = string.Format("Product[{1}]|New Arrival[{0}]", this.ResolveUrl("~/Search.aspx?product=new_arrival"), this.ResolveUrl("~/Search.aspx?category=All_0"));
            }
            else if (prd.IsHotProduct)
            {
                PageMap = string.Format("Product[{1}]|Daily Special[{0}]", this.ResolveUrl("~/Search.aspx?product=daily_special"), this.ResolveUrl("~/Search.aspx?category=All_0"));
            }
            else
            {
                View_CategoryTree c = new View_CategoryTree();
                c.Where.ID.Value = prd.CategoryID;
                c.Query.Load();
                string str = "";
                string[] pathNames = c.s_Path.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
                string[] pathIDs = c.s_IDPath.Split(new string[] { "/" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < pathNames.Length; i++)
                {
                    str += string.Format("{1}[{0}]", this.ResolveUrl(string.Format("~/Search.aspx?category={0}_{1}", Utilities.GetValidParam(pathNames[i]), pathIDs[i])), pathNames[i]);
                    if (i < pathNames.Length - 1)
                        str += "|";
                }

                PageMap = string.Format("Product[{0}]|{1}", this.ResolveUrl("~/Search.aspx?category=All_0"), str);
            }

        }

        protected void btnAddWishList_OnClick(object sender, EventArgs e)
        {
            if (View_Customers.GetCurrentUser() != null && View_Customers.GetCurrentUser().RowCount > 0)
            {
                int id = ProductID;
                POSSystem.BLL.WishList w = POSSystem.BLL.WishList.GetByCustomer(View_Customers.GetCurrentUser().ID, id);
                if (w.RowCount > 0)
                {
                    ScriptManager.RegisterStartupScript(this, typeof(Page), Guid.NewGuid().ToString(), String.Format("showNotification('All For You Online', 'This item has already been added to your WishList!', 8000);", 1), true);
                    return;
                }
                w.AddNew();
                w.CustomerID = View_Customers.GetCurrentUser().ID;
                w.ProductID = id;
                w.CreatedDate = DateTime.UtcNow.AddHours(SystemVariables.SysVars.TimeZone);
                w.Deleted = false;
                w.Save();

                AddedToWishlist = true;
            }
            else
            {
                this.Response.Redirect("Login.aspx?url=Product.aspx" + Request.Url.Query);
            }
        }

        protected void btnAddCart_OnClick(object sender, EventArgs e)
        {
            int id = ProductID;

            View_WebProducts p = View_WebProducts.LoadProductByID(id);

            OrderItems items = BasePage.SelectedItems;
            items.AddNew();
            if (!items.DefaultView.Table.Columns.Contains(BasePage.PRODUCT_IMAGE))
                items.AddColumn(BasePage.PRODUCT_IMAGE, typeof(string));
            items.ProductID = id;
            items.ID = -items.RowCount;
            items.ProductName = p.s_ProductName;
            items.s_Quantity = txtQuantity.Text;
            items.s_CustomerPrice = (SessionUser != null && SessionUser.Price == CustomerType.CustomerPrice.DealerPrice) ? p.s_DealerPrice : ((SessionUser != null && SessionUser.Price == CustomerType.CustomerPrice.PartnerPrice) ? p.s_PartnerPrice : p.s_SalePrice);
            items.s_UnitCost = p.s_Cost;
            items.s_UnitPrice = p.s_SalePrice;
            items.s_UnitDealerPrice = p.s_DealerPrice;
            items.TotalAmount = items.Quantity * items.CustomerPrice;
            items.GST = p.GST ? Math.Round(items.TotalAmount * SystemVariables.SysVars.GST / (SystemVariables.SysVars.GST + 100), 2) : 0;
            items.Deleted = false;
            items.BarCode = p.s_BarCode;
            items.s_ProductImage = p.s_ProductImageID;
            items.Category = OrderItemCategory.Product;
            items.Name = p.ProductName;
            if (items.s_ProductImage != "")
            {
                ProductImages img = ProductImages.GetById(int.Parse(items.s_ProductImage));
                if (img.RowCount > 0)
                    items.SetColumn(BasePage.PRODUCT_IMAGE, MobileShop.Utilities.GetImageUrl(img.s_ThumbUrl));
            }
            else
                items.SetColumn(BasePage.PRODUCT_IMAGE, GetDefaultPic());


            ((ProductMaster)this.Master).UpdateCart();
            AddedToCart = true;
        }
    }
}